import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * API Configuration Panel - Provides API key configuration, source selection and advanced settings
 */
public class APIConfigurationPanel extends JPanel {

    private UserPreferences userPreferences;
    private MultiAPIManager multiAPIManager;

    // API Key components
    private JPasswordField openWeatherKeyField;
    private JPasswordField weatherApiKeyField;
    private JButton testOpenWeatherButton;
    private JButton testWeatherApiButton;
    private JLabel openWeatherStatusLabel;
    private JLabel weatherApiStatusLabel;

    // API Source components
    private JComboBox<String> primarySourceCombo;
    private JComboBox<String> backupSourceCombo;
    private JComboBox<String> aggregationStrategyCombo;

    // Advanced settings
    private JSpinner timeoutSpinner;
    private JSpinner retriesSpinner;
    private JCheckBox failoverCheckBox;

    // Status components
    private JLabel overallStatusLabel;
    private JProgressBar testProgressBar;

    // Layout-related components for dynamic updates
    private JPanel mainContent;
    private JPanel apiKeysPanel;

    public APIConfigurationPanel(UserPreferences userPreferences) {
        this.userPreferences = userPreferences;
        initializeComponents();
        setupLayout();
        loadCurrentSettings();
        setupEventHandlers();
    }

    public void setMultiAPIManager(MultiAPIManager manager) {
        this.multiAPIManager = manager;
    }

    private void initializeComponents() {
        setBackground(ModernUIComponents.Colors.BACKGROUND);
        setLayout(new BorderLayout());

        // API Key fields
        openWeatherKeyField = new JPasswordField(20);
        weatherApiKeyField = new JPasswordField(20);

        // Test buttons
        testOpenWeatherButton = ModernUIComponents.createModernButton("Test", ModernUIComponents.Colors.PRIMARY);
        testWeatherApiButton = ModernUIComponents.createModernButton("Test", ModernUIComponents.Colors.PRIMARY);

        // Status labels
        openWeatherStatusLabel = ModernUIComponents.createModernLabel("Not tested", ModernUIComponents.Fonts.SMALL, ModernUIComponents.Colors.ON_SURFACE_VARIANT);
        weatherApiStatusLabel = ModernUIComponents.createModernLabel("Not tested", ModernUIComponents.Fonts.SMALL, ModernUIComponents.Colors.ON_SURFACE_VARIANT);

        // Source selection
        String[] apiSources = {"openweather", "weatherapi"};
        primarySourceCombo = new JComboBox<>(apiSources);
        backupSourceCombo = new JComboBox<>(apiSources);

        String[] strategies = {
                "PRIMARY_FAILOVER",
                "PARALLEL_AGGREGATE",
                "BEST_PERFORMANCE",
                "USER_SELECTED"
        };
        aggregationStrategyCombo = new JComboBox<>(strategies);

        // Advanced settings
        timeoutSpinner = new JSpinner(new SpinnerNumberModel(8000, 1000, 30000, 1000));
        retriesSpinner = new JSpinner(new SpinnerNumberModel(3, 1, 10, 1));
        failoverCheckBox = new JCheckBox("Enable API Failover");

        // Status components
        overallStatusLabel = ModernUIComponents.createModernLabel("Configuration Status: Unknown", ModernUIComponents.Fonts.BODY_MEDIUM, ModernUIComponents.Colors.ON_SURFACE);
        testProgressBar = new JProgressBar();
        testProgressBar.setVisible(false);
        testProgressBar.setStringPainted(true);
        testProgressBar.setString("Testing...");
    }

    private void setupLayout() {
        mainContent = new JPanel();
        mainContent.setLayout(new BoxLayout(mainContent, BoxLayout.Y_AXIS));
        mainContent.setBackground(ModernUIComponents.Colors.BACKGROUND);
        mainContent.setBorder(BorderFactory.createEmptyBorder(
                ModernUIComponents.Spacing.LG,
                ModernUIComponents.Spacing.LG,
                ModernUIComponents.Spacing.LG,
                ModernUIComponents.Spacing.LG
        ));

        // Title
        JLabel titleLabel = ModernUIComponents.createModernLabel(
                "API Configuration Manager", ModernUIComponents.Fonts.TITLE, ModernUIComponents.Colors.ON_SURFACE);
        titleLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
        mainContent.add(titleLabel);
        mainContent.add(Box.createVerticalStrut(ModernUIComponents.Spacing.XL));

        // API Keys Section
        apiKeysPanel = createAPIKeysSection();
        mainContent.add(apiKeysPanel);
        mainContent.add(Box.createVerticalStrut(ModernUIComponents.Spacing.LG));

        // API Sources Section
        JPanel sourcesPanel = createAPISourcesSection();
        mainContent.add(sourcesPanel);
        mainContent.add(Box.createVerticalStrut(ModernUIComponents.Spacing.LG));

        // Advanced Settings Section
        JPanel advancedPanel = createAdvancedSettingsSection();
        mainContent.add(advancedPanel);
        mainContent.add(Box.createVerticalStrut(ModernUIComponents.Spacing.LG));

        // Status Section
        JPanel statusPanel = createStatusSection();
        mainContent.add(statusPanel);

        // Add glue to push content to top
        mainContent.add(Box.createVerticalGlue());

        add(mainContent, BorderLayout.NORTH);
    }

    private JPanel createAPIKeysSection() {
        JPanel panel = ModernUIComponents.createGlassPanel("");
        panel.setLayout(new BorderLayout());
        panel.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createLineBorder(ModernUIComponents.Colors.OUTLINE_VARIANT),
                "API Configuration & Status",
                TitledBorder.LEFT,
                TitledBorder.TOP,
                ModernUIComponents.Fonts.BODY_MEDIUM,
                ModernUIComponents.Colors.ON_SURFACE
        ));

        JPanel content = new JPanel();
        content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
        content.setOpaque(false);
        content.setBorder(BorderFactory.createEmptyBorder(
                ModernUIComponents.Spacing.MD, ModernUIComponents.Spacing.MD,
                ModernUIComponents.Spacing.MD, ModernUIComponents.Spacing.MD
        ));

        // OpenWeatherMap API Card
        JPanel openWeatherCard = createAPIStatusCard(
                "OpenWeatherMap",
                openWeatherKeyField,
                testOpenWeatherButton,
                openWeatherStatusLabel,
                "openweather"
        );
        content.add(openWeatherCard);
        content.add(Box.createVerticalStrut(ModernUIComponents.Spacing.MD));

        // WeatherAPI.com API Card
        JPanel weatherApiCard = createAPIStatusCard(
                "WeatherAPI.com",
                weatherApiKeyField,
                testWeatherApiButton,
                weatherApiStatusLabel,
                "weatherapi"
        );
        content.add(weatherApiCard);

        panel.add(content, BorderLayout.CENTER);
        panel.setAlignmentX(Component.LEFT_ALIGNMENT);
        panel.setMaximumSize(new Dimension(Integer.MAX_VALUE, panel.getPreferredSize().height));

        return panel;
    }

    private JPanel createAPIStatusCard(String apiName, JPasswordField keyField, JButton testButton, JLabel statusLabel, String sourceId) {
        JPanel card = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                Graphics2D g2 = (Graphics2D) g.create();
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                // Card background
                Color bgColor = ModernUIComponents.Colors.SURFACE_VARIANT;

                if (getMousePosition() != null) {
                    // Hover effect
                    bgColor = ModernUIComponents.Colors.PRIMARY_8;
                }

                g2.setColor(bgColor);
                g2.fillRoundRect(0, 0, getWidth(), getHeight(), 16, 16);

                // Border for outlined style
                g2.setColor(ModernUIComponents.Colors.OUTLINE_VARIANT);
                g2.drawRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 16, 16);

                g2.dispose();
            }
        };

        card.setLayout(new GridBagLayout());
        card.setOpaque(false);
        card.setBorder(BorderFactory.createEmptyBorder(
                ModernUIComponents.Spacing.LG,
                ModernUIComponents.Spacing.LG,
                ModernUIComponents.Spacing.LG,
                ModernUIComponents.Spacing.LG
        ));
        // 增加高度以容纳所有组件
        card.setPreferredSize(new Dimension(0, 110));
        card.setMinimumSize(new Dimension(0, 110));

        GridBagConstraints gbc = new GridBagConstraints();

        // API名称标签 (第一行，跨越所有列)
        gbc.gridx = 0; gbc.gridy = 0;
        gbc.gridwidth = 3;
        gbc.anchor = GridBagConstraints.WEST;
        gbc.insets = new Insets(0, 0, ModernUIComponents.Spacing.SM, 0);

        JLabel nameLabel = ModernUIComponents.createModernLabel(
                apiName + " API Key:",
                ModernUIComponents.Fonts.BODY_LARGE,
                ModernUIComponents.Colors.ON_SURFACE
        );
        card.add(nameLabel, gbc);

        // API密钥输入框 (第二行，左侧)
        gbc.gridx = 0; gbc.gridy = 1;
        gbc.gridwidth = 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        gbc.insets = new Insets(0, 0, 0, ModernUIComponents.Spacing.MD);

        keyField.setPreferredSize(new Dimension(250, 36));
        keyField.setMinimumSize(new Dimension(200, 36));
        card.add(keyField, gbc);

        // 测试按钮 (第二行，中间)
        gbc.gridx = 1; gbc.gridy = 1;
        gbc.fill = GridBagConstraints.NONE;
        gbc.weightx = 0.0;
        gbc.anchor = GridBagConstraints.CENTER;
        gbc.insets = new Insets(0, ModernUIComponents.Spacing.SM, 0, ModernUIComponents.Spacing.SM);

        testButton.setPreferredSize(new Dimension(100, 36));
        testButton.setMinimumSize(new Dimension(80, 36));
        card.add(testButton, gbc);

        // 状态芯片 (第二行，右侧)
        gbc.gridx = 2; gbc.gridy = 1;
        gbc.anchor = GridBagConstraints.EAST;
        // Increase left inset to add more space
        gbc.insets = new Insets(0, ModernUIComponents.Spacing.MD, 0, 0);

        JPanel statusChip = createStatusChip(statusLabel.getText(), getStatusColor(statusLabel.getText()));
        statusChip.setPreferredSize(new Dimension(120, 32));
        card.add(statusChip, gbc);

        return card;
    }

    private JPanel createStatusChip(String statusText, Color statusColor) {
        return ModernUIComponents.createMD3StatusChip(statusText, statusColor);
    }

    private Color getStatusColor(String statusText) {
        if (statusText.contains("Available") || statusText.contains("✓")) {
            return ModernUIComponents.Colors.SUCCESS;
        } else if (statusText.contains("Error") || statusText.contains("✗") || statusText.contains("Not available")) {
            return ModernUIComponents.Colors.ERROR;
        } else if (statusText.contains("Testing")) {
            return ModernUIComponents.Colors.WARNING;
        } else {
            return ModernUIComponents.Colors.OUTLINE;
        }
    }

    private JPanel createAPISourcesSection() {
        JPanel panel = ModernUIComponents.createGlassPanel("");
        panel.setLayout(new BorderLayout());
        panel.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createLineBorder(ModernUIComponents.Colors.OUTLINE_VARIANT),
                "API Source Configuration",
                TitledBorder.LEFT,
                TitledBorder.TOP,
                ModernUIComponents.Fonts.BODY_MEDIUM,
                ModernUIComponents.Colors.ON_SURFACE
        ));

        JPanel content = new JPanel(new GridBagLayout());
        content.setOpaque(false);
        content.setBorder(BorderFactory.createEmptyBorder(
                ModernUIComponents.Spacing.LG,
                ModernUIComponents.Spacing.LG,
                ModernUIComponents.Spacing.LG,
                ModernUIComponents.Spacing.LG
        ));

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(ModernUIComponents.Spacing.MD, 0, ModernUIComponents.Spacing.MD, ModernUIComponents.Spacing.LG);
        gbc.anchor = GridBagConstraints.WEST;

        // Primary source
        gbc.gridx = 0; gbc.gridy = 0;
        gbc.weightx = 0.0;
        JLabel primaryLabel = ModernUIComponents.createModernLabel("Primary API Source:",
                ModernUIComponents.Fonts.BODY_MEDIUM, ModernUIComponents.Colors.ON_SURFACE);
        primaryLabel.setPreferredSize(new Dimension(180, 32));
        content.add(primaryLabel, gbc);

        gbc.gridx = 1; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weightx = 1.0;
        primarySourceCombo.setPreferredSize(new Dimension(200, 36));
        content.add(primarySourceCombo, gbc);

        // Backup source
        gbc.gridx = 0; gbc.gridy = 1; gbc.fill = GridBagConstraints.NONE; gbc.weightx = 0.0;
        JLabel backupLabel = ModernUIComponents.createModernLabel("Backup API Source:",
                ModernUIComponents.Fonts.BODY_MEDIUM, ModernUIComponents.Colors.ON_SURFACE);
        backupLabel.setPreferredSize(new Dimension(180, 32));
        content.add(backupLabel, gbc);

        gbc.gridx = 1; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weightx = 1.0;
        backupSourceCombo.setPreferredSize(new Dimension(200, 36));
        content.add(backupSourceCombo, gbc);

        // Aggregation strategy
        gbc.gridx = 0; gbc.gridy = 2; gbc.fill = GridBagConstraints.NONE; gbc.weightx = 0.0;
        JLabel strategyLabel = ModernUIComponents.createModernLabel("Aggregation Strategy:",
                ModernUIComponents.Fonts.BODY_MEDIUM, ModernUIComponents.Colors.ON_SURFACE);
        strategyLabel.setPreferredSize(new Dimension(180, 32));
        content.add(strategyLabel, gbc);

        gbc.gridx = 1; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weightx = 1.0;
        aggregationStrategyCombo.setPreferredSize(new Dimension(200, 36));
        content.add(aggregationStrategyCombo, gbc);

        panel.add(content, BorderLayout.CENTER);
        panel.setAlignmentX(Component.LEFT_ALIGNMENT);
        panel.setMaximumSize(new Dimension(Integer.MAX_VALUE, panel.getPreferredSize().height));

        return panel;
    }

    private JPanel createAdvancedSettingsSection() {
        JPanel panel = ModernUIComponents.createGlassPanel("");
        panel.setLayout(new BorderLayout());
        panel.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createLineBorder(ModernUIComponents.Colors.OUTLINE_VARIANT),
                "Advanced Settings",
                TitledBorder.LEFT,
                TitledBorder.TOP,
                ModernUIComponents.Fonts.BODY_MEDIUM,
                ModernUIComponents.Colors.ON_SURFACE
        ));

        JPanel content = new JPanel(new GridBagLayout());
        content.setOpaque(false);
        content.setBorder(BorderFactory.createEmptyBorder(
                ModernUIComponents.Spacing.LG,
                ModernUIComponents.Spacing.LG,
                ModernUIComponents.Spacing.LG,
                ModernUIComponents.Spacing.LG
        ));

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(ModernUIComponents.Spacing.MD, 0, ModernUIComponents.Spacing.MD, ModernUIComponents.Spacing.LG);
        gbc.anchor = GridBagConstraints.WEST;

        // Timeout
        gbc.gridx = 0; gbc.gridy = 0;
        gbc.weightx = 0.0;
        JLabel timeoutLabel = ModernUIComponents.createModernLabel("Connection Timeout (ms):",
                ModernUIComponents.Fonts.BODY_MEDIUM, ModernUIComponents.Colors.ON_SURFACE);
        timeoutLabel.setPreferredSize(new Dimension(180, 32));
        content.add(timeoutLabel, gbc);

        gbc.gridx = 1; gbc.weightx = 1.0;
        timeoutSpinner.setPreferredSize(new Dimension(120, 36));
        content.add(timeoutSpinner, gbc);

        // Retries
        gbc.gridx = 0; gbc.gridy = 1; gbc.weightx = 0.0;
        JLabel retriesLabel = ModernUIComponents.createModernLabel("Max Retries:",
                ModernUIComponents.Fonts.BODY_MEDIUM, ModernUIComponents.Colors.ON_SURFACE);
        retriesLabel.setPreferredSize(new Dimension(180, 32));
        content.add(retriesLabel, gbc);

        gbc.gridx = 1; gbc.weightx = 1.0;
        retriesSpinner.setPreferredSize(new Dimension(120, 36));
        content.add(retriesSpinner, gbc);

        // Failover checkbox
        gbc.gridx = 0; gbc.gridy = 2; gbc.gridwidth = 2;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(ModernUIComponents.Spacing.LG, 0, 0, 0);
        failoverCheckBox.setPreferredSize(new Dimension(0, 36));
        content.add(failoverCheckBox, gbc);

        panel.add(content, BorderLayout.CENTER);
        panel.setAlignmentX(Component.LEFT_ALIGNMENT);
        panel.setMaximumSize(new Dimension(Integer.MAX_VALUE, panel.getPreferredSize().height));

        return panel;
    }

    private JPanel createStatusSection() {
        JPanel panel = ModernUIComponents.createGlassPanel("");
        panel.setLayout(new BorderLayout());
        panel.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createLineBorder(ModernUIComponents.Colors.OUTLINE_VARIANT),
                "Configuration Status",
                TitledBorder.LEFT,
                TitledBorder.TOP,
                ModernUIComponents.Fonts.BODY_MEDIUM,
                ModernUIComponents.Colors.ON_SURFACE
        ));

        JPanel content = new JPanel(new BorderLayout());
        content.setOpaque(false);
        content.setBorder(BorderFactory.createEmptyBorder(
                ModernUIComponents.Spacing.LG,
                ModernUIComponents.Spacing.LG,
                ModernUIComponents.Spacing.LG,
                ModernUIComponents.Spacing.LG
        ));

        // 设置状态标签样式
        overallStatusLabel.setHorizontalAlignment(SwingConstants.LEFT);
        overallStatusLabel.setPreferredSize(new Dimension(0, 40));
        content.add(overallStatusLabel, BorderLayout.NORTH);

        // 进度条容器
        JPanel progressContainer = new JPanel(new BorderLayout());
        progressContainer.setOpaque(false);
        progressContainer.setBorder(BorderFactory.createEmptyBorder(
                ModernUIComponents.Spacing.MD, 0, 0, 0
        ));

        testProgressBar.setPreferredSize(new Dimension(0, 32));
        progressContainer.add(testProgressBar, BorderLayout.CENTER);
        content.add(progressContainer, BorderLayout.CENTER);

        panel.add(content, BorderLayout.CENTER);
        panel.setAlignmentX(Component.LEFT_ALIGNMENT);
        panel.setMaximumSize(new Dimension(Integer.MAX_VALUE, panel.getPreferredSize().height));

        return panel;
    }

    private void setupEventHandlers() {
        // API key change handlers
        openWeatherKeyField.addActionListener(e -> saveApiKey("openweather"));
        weatherApiKeyField.addActionListener(e -> saveApiKey("weatherapi"));

        // Test button handlers
        testOpenWeatherButton.addActionListener(e -> testApiKey("openweather"));
        testWeatherApiButton.addActionListener(e -> testApiKey("weatherapi"));

        // Source selection handlers
        primarySourceCombo.addActionListener(e -> saveSourceSelection());
        backupSourceCombo.addActionListener(e -> saveSourceSelection());
        aggregationStrategyCombo.addActionListener(e -> saveAggregationStrategy());

        // Advanced settings handlers
        timeoutSpinner.addChangeListener(e -> saveAdvancedSettings());
        retriesSpinner.addChangeListener(e -> saveAdvancedSettings());
        failoverCheckBox.addActionListener(e -> saveAdvancedSettings());
    }

    private void loadCurrentSettings() {
        // Load API keys
        openWeatherKeyField.setText(userPreferences.getOpenWeatherMapApiKey());
        weatherApiKeyField.setText(userPreferences.getWeatherApiComKey());

        // Load source selections
        primarySourceCombo.setSelectedItem(userPreferences.getPrimaryApiSource());
        backupSourceCombo.setSelectedItem(userPreferences.getBackupApiSource());
        aggregationStrategyCombo.setSelectedItem(userPreferences.getAggregationStrategy());

        // Load advanced settings
        timeoutSpinner.setValue(userPreferences.getApiTimeout());
        retriesSpinner.setValue(userPreferences.getMaxRetries());
        failoverCheckBox.setSelected(userPreferences.isEnableApiFailover());

        // Update status
        updateOverallStatus();
    }

    private void saveApiKey(String source) {
        if ("openweather".equals(source)) {
            String key = new String(openWeatherKeyField.getPassword());
            userPreferences.setOpenWeatherMapApiKey(key);
        } else if ("weatherapi".equals(source)) {
            String key = new String(weatherApiKeyField.getPassword());
            userPreferences.setWeatherApiComKey(key);
        }
        updateOverallStatus();
    }

    private void saveSourceSelection() {
        userPreferences.setPrimaryApiSource((String) primarySourceCombo.getSelectedItem());
        userPreferences.setBackupApiSource((String) backupSourceCombo.getSelectedItem());
        updateOverallStatus();
    }

    private void saveAggregationStrategy() {
        userPreferences.setAggregationStrategy((String) aggregationStrategyCombo.getSelectedItem());
        updateOverallStatus();
    }

    private void saveAdvancedSettings() {
        userPreferences.setApiTimeout((Integer) timeoutSpinner.getValue());
        userPreferences.setMaxRetries((Integer) retriesSpinner.getValue());
        userPreferences.setEnableApiFailover(failoverCheckBox.isSelected());
        updateOverallStatus();
    }

    private void testApiKey(String source) {
        JButton testButton = "openweather".equals(source) ? testOpenWeatherButton : testWeatherApiButton;
        JLabel statusLabel = "openweather".equals(source) ? openWeatherStatusLabel : weatherApiStatusLabel;

        testButton.setEnabled(false);
        statusLabel.setText("Testing...");
        statusLabel.setForeground(ModernUIComponents.Colors.ON_SURFACE_VARIANT);
        testProgressBar.setVisible(true);
        testProgressBar.setIndeterminate(true);

        // Save current API key before testing
        saveApiKey(source);

        CompletableFuture.supplyAsync(() -> {
                    try {
                        if (multiAPIManager != null) {
                            // Test using MultiAPIManager
                            for (WeatherAPIService service : multiAPIManager.getRegisteredServices()) {
                                if (service.getSourceId().equals(source)) {
                                    long latency = service.testConnection();
                                    return latency > 0;
                                }
                            }
                        } else {
                            // Fallback test
                            if ("openweather".equals(source)) {
                                WeatherAPIManager manager = new WeatherAPIManager(userPreferences);
                                return manager.isServiceAvailable();
                            } else if ("weatherapi".equals(source)) {
                                WeatherAPIComService service = new WeatherAPIComService(userPreferences);
                                return service.isServiceAvailable();
                            }
                        }
                        return false;
                    } catch (Exception e) {
                        return false;
                    }
                }).orTimeout(10, TimeUnit.SECONDS)
                .whenComplete((success, throwable) -> {
                    SwingUtilities.invokeLater(() -> {
                        testButton.setEnabled(true);
                        testProgressBar.setVisible(false);
                        testProgressBar.setIndeterminate(false);

                        if (throwable != null) {
                            statusLabel.setText("Test timeout");
                            statusLabel.setForeground(ModernUIComponents.Colors.ERROR);
                        } else if (success) {
                            statusLabel.setText("Available");
                            statusLabel.setForeground(Color.GREEN);
                        } else {
                            statusLabel.setText("Not available");
                            statusLabel.setForeground(ModernUIComponents.Colors.ERROR);
                        }

                        // 重新创建API密钥section以更新状态芯片
                        recreateAPIKeysSection();
                        updateOverallStatus();
                    });
                });
    }

    private void updateOverallStatus() {
        SwingUtilities.invokeLater(() -> {
            boolean hasValidKey = userPreferences.hasAnyValidApiKey();
            String status;
            Color color;

            if (hasValidKey) {
                status = "Configuration Status: API keys are valid";
                color = Color.GREEN;
            } else {
                status = "Configuration Status: API keys are not configured";
                color = ModernUIComponents.Colors.ERROR;
            }

            overallStatusLabel.setText(status);
            overallStatusLabel.setForeground(color);
        });
    }

    /**
     * Refresh API service status
     */
    public void refreshServiceStatus() {
        if (multiAPIManager != null) {
            // Reset status labels
            openWeatherStatusLabel.setText("Checking...");
            weatherApiStatusLabel.setText("Checking...");

            // Check each service
            for (WeatherAPIService service : multiAPIManager.getRegisteredServices()) {
                String sourceId = service.getSourceId();
                boolean available = service.isServiceAvailable();

                SwingUtilities.invokeLater(() -> {
                    JLabel statusLabel = "openweather".equals(sourceId) ?
                            openWeatherStatusLabel : weatherApiStatusLabel;

                    if (available) {
                        statusLabel.setText("Available");
                        statusLabel.setForeground(Color.GREEN);
                    } else {
                        statusLabel.setText("Not available");
                        statusLabel.setForeground(ModernUIComponents.Colors.ERROR);
                    }

                    // Force recreation of the API keys section to update status chips
                    recreateAPIKeysSection();
                });
            }
        }
        updateOverallStatus();
    }

    private void recreateAPIKeysSection() {
        if (mainContent != null && apiKeysPanel != null) {
            // Find the index of the old panel
            int index = -1;
            for (int i = 0; i < mainContent.getComponentCount(); i++) {
                if (mainContent.getComponent(i) == apiKeysPanel) {
                    index = i;
                    break;
                }
            }

            if (index != -1) {
                // Remove the old panel
                mainContent.remove(apiKeysPanel);

                // Create and add the new panel at the same index
                this.apiKeysPanel = createAPIKeysSection();
                mainContent.add(this.apiKeysPanel, index);

                // Revalidate and repaint the container
                mainContent.revalidate();
                mainContent.repaint();
            }
        }
    }
} 